<?php

/*
Title:   'STatistics plugin' 
Project: 'STatistics'
Coder:   'manodvaravajjana' 
subcoder:''
*/


chdir(dirname(__FILE__)."/../..");
$path = getcwd();
chdir("../");
$path3 = getcwd();
chdir(dirname(__FILE__));
#debug($path3 , $path2);
include_once $path3."/lib/core.class.php";

/* HEADER INCLUDES */

$src_path = getcwd();
//include $src_path.('/config.php');

    $core = getCoreInstance();
    $GLOBALS["host"]=$core->config["DB"]["hostspec"];
    $GLOBALS["usr"]=$core->config["DB"]["username"];
    $GLOBALS["passw"]=$core->config["DB"]["password"];
    $GLOBALS["db"]=$core->config["DB"]["database"];
    $GLOBALS["site"]=$core->config["system"]["http_root"];

$src_path.='/src';

require $src_path.('/config.inc.php');
include $src_path.('/get_conf.inc.php');
include $src_path.('/register_globals_off.php');

/* BODY INCLUDES */
//require $src_path.('/config.inc.php');
//include $src_path.('/log_func.php');

class Vstats extends IPlugin 
{
    var $color;
    
    function Vstats ($parent = null)
    {
        IPlugin::IPlugin($parent);
        $this->tplfolder = dirname(__FILE__)."/tpl";
        $this->color = "green";
    }
    
    function getPluginTag() { return "vstat"; }
    function getPluginName() { return "Vstats Plugin"; }
    function getPluginVersion() { return "1.0.0"; }
    
    function getProperty($p = null)
    {
        if(null == $p)
        {
            return array("MenuTitle", "MenuBlockTitle");

        }
        $result = "";
        switch ($p)
        {
            case "MenuBlockTitle": { return "Site Monitoring"; } break;
            case "MenuTitle" : { return "Site Visiting"; } break;
        };

        return $result;
    }
    
    // ----------------------------------------------------------------------------------
    // --- [ Handling all actions ] -----------------------------------------------------
    // ----------------------------------------------------------------------------------

    function doAction($params)
    {
        if(null != ($result = IPlugin::doAction($params)))
        {
            return $result;

        }

  

        switch ($_POST["event"]) {
            case "none": {

            } break;

            default:
            break;
        }
        
        
        
        
    }


    // ----------------------------------------------------------------------------------
    // --- [ Render switch pages ] -------------------------------------------------------------
    // ----------------------------------------------------------------------------------

    function Render($params)
    {
        global $_G;
        if(null != ($result = IPlugin::Render($params)))
        {
            return $result;
        }
        
        $core = &getCoreInstance();
        $db = $core->getProperty("db");
        $framework = $core->getProperty("framework");
        $render = $framework->smarty;
        $render->assign("baseurl", "?".$this->getURL()."&page=".$_G["page"]);

        $page = "";
        switch ($_G["page"]) {
            case "print":
                $page = $this->renderprint($render);
                break;


            case "read":
                $page = $this->renderraw($core, $render, $db);
                break;

            case "empty":
            $render->assign("url", "?".$this->getURL());
        $sql = "delete from ez_zstat";
        $db->Exec($sql);
                $page = $this->RenderIndex2($core, $render, $db);
                break;

            default:
                $page = $this->RenderIndex2($core, $render, $db);
                break;
        }

        return $render->fetch("file:".$this->tplfolder."/".$page);
    }
    

    // ----------------------------------------------------------------------------------
    // --- [ Render source ] ------------------------------------------------------------
    // ----------------------------------------------------------------------------------
    function cb_renderNewslist($data)
    {
        $dt = array(
                array($data["id"] , "align=\"center\""),
                array($data["os"] , ""),
                array($data["wb"] , ""),
                array($data["request"] , ""),
                array($data["host"] , ""),
                array($data["address"] , ""),
                array($data["agent"] , ""),
                array($data["date"] , ""),
                array($data["referer"] , ""),
                array($data["country"] , "") ,
                array($data["provider"] , "")

                );
//      debug($dt, "CBfunction");
        return $dt;
    }


    function renderprint(&$render)
    {

        $core = getCoreInstance();
        $db = $core->getProperty("db");
        
        $pg = &$core->getSnippet("paginator");
//      debug($pg, get_class($pg));

        $stp = $_GET['stp'];
        $params = array(
                    "cb_class" => &$this,
                    "cb_func" => cb_renderNewslist,
                    "urlbase" => $this->getURL(),
                    "caption" => "",
                    "emptymsg" => "No statistic collected yet",
                    "header" => array("ID", "OS", "Browser","Request", "Host", "Address","Agent","Date","Referer", "Country","Provider"),
                    "items" => "",
                    "source" => "sql", // -- sql, array
                    "sql_items" => "select * from ez_zstat order by $stp",
                    "sql_count" => "select count(*) from ez_zstat",
                    "ippg" => 4500, // -- items per page
                    "nppv" => 2, // -- number pages per view
                    );
        $HTML = $pg->Render($params);
        $render->assign('HTML',$HTML);

        return "print.tpl.php";
    }


      function renderraw(&$core, &$render, &$db)
    {

return "read.tpl.php";



    }

    // ----------------------------------------------------------------------------------
    // --- [ Render source ] ------------------------------------------------------------
    // ----------------------------------------------------------------------------------


    function AL_Date()  {
    $r = date("l dS of F Y h:i:s A");
    return($r);
                    }

    function make_titre($arg0)  {
    $sites = $arg0;
    $r = "<a style=\"text-decoration: none;\" href="."'"."".$sites['ez_zstat']."'"." target='_blank'>".$sites['ez_zstat']."</a>";
    return($r);
                    }

    function day($arg0,$arg1) {
    $table = $arg1;
    $d = $table."&reqdate=".time()."&reset=0"."&period=jour";
    $w = $table."&reqdate=".time()."&reset=0"."&period=semaine";
    $m = $table."&reqdate=".time()."&reset=0"."&period=mois";

if ($arg0 == 'd')
{
    $period = 'jour';
    return ($d);
}
else if ($arg0 == 'w')
{
    $period = 'semaine';
    return ($w);
}
else if ($arg0 == 'm')
{
    $period = 'mois';
    return ($m);
}

                     }
    function showrowlogs($arg0,$arg1,$arg2)  {
    $table = $arg0;
    $per_iod = $arg1;
    $req_date = $arg2;
    $r = '&page=read&table='.$table.'&period='.$per_iod.'&reqdate='.$req_date;
    return($r);
                    }

    function pday($arg0,$arg1,$arg2)                    {
    $per_iod  = $arg0;
    $req_date = $arg1;
    $tab_le   = $arg2;
    if ($per_iod == 'jour'){
    $ysreqdate = $req_date - 86400;
    $r = '&table='.$tab_le.'&reqdate='.$ysreqdate.'&reset=0'.'&period='.$per_iod;
                           }
    if ($per_iod == 'semaine'){
    $ysreqdate = $req_date - 7*86400;
    $r = '&table='.$tab_le.'&reqdate='.$ysreqdate.'&reset=0'.'&period='.$per_iod;
                           }
    return($r);
                                            }

    function nday($arg0,$arg1,$arg2)                    {

    $per_iod  = $arg0;
    $req_date = $arg1;
    $tab_le   = $arg2;
    if ($per_iod == 'jour'){
    $tmreqdate = $req_date + 86400;
    $r = '&table='.$tab_le.'&reqdate='.$tmreqdate.'&reset=0'.'&period='.$per_iod;
                           }
    if ($per_iod == 'semaine'){
    $tmreqdate = $req_date + 7*86400;
    $r = '&table='.$tab_le.'&reqdate='.$tmreqdate.'&reset=0'.'&period='.$per_iod;
                           }
    return($r);
                                            }


##################################################################################
# This function will output in html format a table
# with a title ($title) and a list of Items with corresponding
# bar graph representing percentage
# $val must be an array such as:
#    [Total] => 20
#    [Win95] => 12
#    [Win98] => 7
#    [WinNT] => 1
##################################################################################
function ProcessBarGraph($title, $val,$per,$tabl,$reqdat) {
//$src_path = getcwd().'/src';
//require $src_path.('/config.inc.php');
//include $src_path.('/log_func.php');
 $readurl = $this->getURL();
 $period  = $per;
 $table   = $tabl;
 $reqdate = $reqdat;
 
 $msgCountrySort = 'Country sort';
 $msgBrowserSort = 'Browser sort';
 $msgOsSort = 'OS sort';
 $msgProviderSort = 'Provider sort';

 $url_trunc_size = 20;
 $r = '';

 $r  = "<table width=\"350\" border=\"0\" cellspacing=\"0\" cellpadding=\"3\" class=\"normal\">";
 $r .= "<tr bgcolor=\"#CCCCCC\">";
 $r .= "<td colspan=\"2\"><b>".$title."</b></td>";
 $r .= "<td width=\"0\">"."<div align=\"center\">"."Hits"."</div></td>";
 $r .= "<td>"."<div align=\"center\">"."%"."</div></td>";
 $r .="</tr>";
// echo "<tr  onMouseover=\"this.bgColor='#EEEEEE'\" onMouseout=\"this.bgColor='$color'\">";

 $sta = true;

 # Find max of percentage
 $temparray = $val;
 $temparray[Total] = 0;
 if ($val["Total"]>0) $maxpcbar = 100 * max($temparray) / $val["Total"];

 while (($bar=each($val)) && ($val[Total]<> 0)) {
   if ($bar[0]<>"Total") {
      if ($sta) { $color = "#CCCCFF" ; } else { $color = "#FFFFCC" ;}
      $pcbar = round(100 * $bar[1] / $val["Total"]);
      $barwidth = round(100 * $pcbar / $maxpcbar);

      $r .= "<tr bgcolor=\"$color\" onMouseover=\"this.bgColor='#FF9999'\" onMouseout=\"this.bgColor='$color'\">";

      # title

      if (substr($bar[0],0,4)=="http") {
//          $r .= "<td width=\"180\">"."<a href=\"read.php?table=".$table."&period=".$period."&reqdate=".$reqdate."&stp=referer&stp2=".urlencode($bar[0])."\"><img src=\"image/question.gif\" width=\"12\" height=\"16\" border=\"0\"></a> "."<a href=\"".$bar[0]."\" target=\"_blank\">".substr($bar[0],7,$url_trunc_size)."</a>"."</td>";
            $r .= "<td width=\"180\">"."<a  href=\"./?$readurl&page=read&table=".$table."&period=".$period."&reqdate=".$reqdate."&stp=referer&stp2=".urlencode($bar[0])."\"><img src=\"image/question.gif\" width=\"12\" height=\"16\" border=\"0\"></a> "."<a href=\"".$bar[0]."\" target=\"_blank\">".substr($bar[0],7,$url_trunc_size)."</a>"."</td>";

      } else

       if (substr($bar[0],1,4)=="http") {
            $r .= "<td width=\"180\">"."<a  href=\"./?$readurl&page=read&table=".$table."&period=".$period."&reqdate=".$reqdate."&stp=referer&stp2=".urlencode($bar[0])."\"><img src=\"image/question.gif\" width=\"12\" height=\"16\" border=\"0\"></a> "."<a href=\"".$bar[0]."\" target=\"_blank\">".substr($bar[0],7,$url_trunc_size)."</a>"."</td>";
      } else




      // Special link for country
      if ($title==$msgCountrySort ) {
            $r .= "<td width=\"180\">"."<a  onclick=\"script: popUp('./?$readurl&doPrint=doPrint&showCloseButton=0&page=print&table=$table&period=$period&reqdate=$reqdate&stp=country&stp2={$bar[0]}');\" href=\"#\">".$bar[0]."</a>"."</td>";
      } else
      // Special link for browser
      if ($title==$msgBrowserSort ) {
          $r .= "<td width=\"180\">"."<a  href=\"#\">".$bar[0]."</a>"."</td>";
//          $r .= "<td width=\"180\">"."<a  href=\"./?$readurl&page=read&table=".$table."&period=".$period."&reqdate=".$reqdate."&stp=wb&stp2=".$bar[0]."\">".$bar[0]."</a>"."</td>";

//        $r .= "<td width=\"180\">"."<a  onclick=\"script: popUp('./?$readurl&page=read&table=$table&period=$period&reqdate=$reqdate&stp=wb&stp2={$bar[0]}');\" href=\"#\">".$bar[0]."</a>"."</td>";

      } else
      // Special link for OS
      if ($title==$msgOsSort ) {
            $xbar = urlencode($bar[0]);
            $r .= "<td width=\"180\">"."<a onclick=\"script: popUp('./?$readurl&doPrint=doPrint&showCloseButton=0&page=print&table=$table&period=$period&reqdate=$reqdate&stp=os&stp2={$xbar}');\"  href=\"#\">".$bar[0]."</a>"."</td>";
//          $r .= "<td width=\"180\">"."<a onclick=\"script: popUp(\'./?$readurl&page=read&table=$table&period=$period&reqdate=$reqdate&stp=os&stp2={$bar[0]}\');\"  href=\"./?$readurl&page=read&table=".$table."&period=".$period."&reqdate=".$reqdate."&stp=os&stp2=".$bar[0]."\">".$bar[0]."</a>"."</td>";
//          $r .= "<td width=\"180\">"."<a onclick=\"script: popUp('./?$readurl&page=read&table=$table&period=$period&reqdate=$reqdate&stp=os&stp2={$bar[0]}');\" href=\"#\">".$bar[0]."</a>"."</td>";





      } else
      // Special link for provider
      if ($title==$msgProviderSort ) {
          
          $r .= "<td width=\"180\">"."<a  href=\"./?$readurl&page=read&table=".$table."&period=".$period."&reqdate=".$reqdate."&stp=provider&stp2=".$bar[0]."\">".$bar[0]."</a>"."</td>";
//            $r .= "<td width=\"180\">"."<a  onclick=\"script: popUp('./?$readurl&page=read&table=$table&period=$period&reqdate=$reqdate&stp=provider&stp2={$bar[0]}');\" href=\"#\">".$bar[0]."</a>"."</td>";
      } else
      //Regular display: no link
      $r .= "<td width=\"180\">".$bar[0]."</td>";

      # List of stuff
      $r .= "<td width=\"170\">";
      # Start of bar graph
      $r .= "<img src=\"image/bar_1.gif\" width=\"1\" height=\"12\" alt=\"$bar[1] hits  -  $pcbar %\">";
      # Bar graph itself
      $r .= "<img src=\"image/bar_1u.gif\" width=\"$barwidth\" height=\"12\" alt=\"$bar[1] hits  -  $pcbar %\">";
      # End of bar graph
      $r .= "<img src=\"image/bar_1.gif\" width=\"1\" height=\"12\" alt=\"$bar[1] hits  -  $pcbar %\">";
      $r .= "</td>";

      $r .= "<td>"."<div align=\"center\">".$bar[1]."</div></td>";
      $r .= "<td>"."<div align=\"center\">".$pcbar."%</div></td>";

      $r .= "</tr>";
      $sta = !$sta;

   }
 }
    # print total
   $r .= "<tr bgcolor=\"#CCCCCC\">";
   $r .= "<td colspan=\"4\"><div align=\"right\">Total: ".$val[Total]."</div></td>";
   $r .= "<tr>";

   $r .= "</table>";
   return($r); 
} # end of fucntion ProcessBarGraph


/////////////////////////////////////////////////////////////////////////
//////////////////////////////////MAIN RENDER////////////////////////////
/////////////////////////////////////////////////////////////////////////



    function RenderIndex2(&$core,&$render,&$db) {
                        /* CONFIGS */

    
    $host=$GLOBALS["host"];
    $usr=$GLOBALS["usr"];
    $passw=$GLOBALS["passw"];
    $db=$core->config["DB"]["database"]; //$GLOBALS["db"];
    $site_name=$GLOBALS["site"];
    
    $table = 'ez_zstat';
    $conf_tabl = 'ez_webstats_conf';

    $_SESSION['nhost']          = $host;
    $_SESSION['nusr']           = $usr;
    $_SESSION['npassw']         = $passw;
    $_SESSION['ndb']            = $db;
    $_SESSION['conf_table']     = $conf_tabl;

  $site=$GLOBALS["site"];
  $sites = array( "ez_zstat"=> $site);

    $render->assign('url',$this->getURL());
    global $period;

                    /* HEADER & SUB HEADER */
        
    $reqdate = isset($_GET['reqdate']) ? $_GET['reqdate'] : time();
    $aldate = $this->AL_Date();
    $render->assign('aldate',$aldate);

    $titre = $this->make_titre($sites);
    $render->assign('titre',$titre);

    $table_day = $this->day('d',$table);
    $render->assign('table_d',$table_day);

    $table_week = $this->day('w',$table);
    $render->assign('table_w',$table_week);

    $table_month = $this->day('m',$table);
    $render->assign('table_m',$table_month);

    $render->assign('period', $period);

    $show_rl = $this->showrowlogs($table,$period,$reqdate);
    $render->assign('srl',$show_rl);

    $pday = $this->pday($period,$reqdate,$table);
    $render->assign('pday',$pday);
    $nday = $this->nday($period,$reqdate,$table);
    $render->assign('nday',$nday);

                    /* BODY I*/

    $table_log = $table;
    $this->ProcessEmptyEntry($table_log); /* Fill empty tables os, browser, country */
    $today   = date("Y-m-d" , $reqdate);
    $today_2 = getdate($reqdate);

if ($period == "jour"  )
{
$msgDaysArray = array("Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday");
$msgMonthsArray = array("january","february","march","april","may","june","july","august","september","october","november","december");
$title = $msgDaysArray[$today_2[wday]]." ".$today_2[mday]." ".$msgMonthsArray[$today_2[mon]-1]." ".$today_2[year];
$hval  = $this->HourSort($table_log, $reqdate );
$byh   = $this->ProcessBarGraph($title,$hval,$period,$table,$reqdate);
$render->assign('byh',$byh);
}

if ($period == 'semaine')  /* Show daily statistics only when month/sort */
{
$xval  = $this->DaySort($table_log, $reqdate, $period );
$byd   = $this->ProcessBarGraph('Daily sort',$xval,$period,$table,$reqdate);
$render->assign('byd',$byd);
}
$xval  = $this->MonthSort($table_log, $reqdate);
$bym   = $this->ProcessBarGraph('Monthly sort',$xval,$period,$table,$reqdate);
$render->assign('bym',$bym);

$xval  = $this->getValx("os",$reqdate,$period,$sites);
$osbar = $this->ProcessBarGraph('OS sort',$xval,$period,$table,$reqdate);
$render->assign('osbar',$osbar);

$xval  = $this->getValx("country",$reqdate,$period,$sites);
$countrybar = $this->ProcessBarGraph('Country sort',$xval,$period,$table,$reqdate);
$render->assign('countrybar',$countrybar);

$xval  = $this->getValx("wb",$reqdate,$period,$sites);
$wbbar = $this->ProcessBarGraph('Browser sort',$xval,$period,$table,$reqdate);
$render->assign('wbbar',$wbbar);



                    /* /BODY I*/
                    /* BODY II*/
/*
if (($period == "jour"))
$byh["Total"] = 1;
*/
if ( ($period == "jour") and ($byh["Total"]>0) ) {
$render->assign('jkey','jour');
       $valjour = $byh;
       $title = $msgDaysArray[$today_2[wday]]." ".$today_2[mday]." ".$msgMonthsArray[$today_2[mon]-1]." ".$today_2[year];
       if ($valjour["0 h"] =="") $valjour["0 h"]="0";
       if ($valjour["1 h"] =="") $valjour["1 h"]="0";
       if ($valjour["2 h"] =="") $valjour["2 h"]="0";
       if ($valjour["3 h"] =="") $valjour["3 h"]="0";
       if ($valjour["4 h"] =="") $valjour["4 h"]="0";
       if ($valjour["5 h"] =="") $valjour["5 h"]="0";
       if ($valjour["6 h"] =="") $valjour["6 h"]="0";
       if ($valjour["7 h"] =="") $valjour["7 h"]="0";
       if ($valjour["8 h"] =="") $valjour["8 h"]="0";
       if ($valjour["9 h"] =="") $valjour["9 h"]="0";
       if ($valjour["10 h"] =="") $valjour["10 h"]="0";
       if ($valjour["11 h"] =="") $valjour["11 h"]="0";
       if ($valjour["12 h"] =="") $valjour["12 h"]="0";
       if ($valjour["13 h"] =="") $valjour["13 h"]="0";
       if ($valjour["14 h"] =="") $valjour["14 h"]="0";
       if ($valjour["15 h"] =="") $valjour["15 h"]="0";
       if ($valjour["16 h"] =="") $valjour["16 h"]="0";
       if ($valjour["17 h"] =="") $valjour["17 h"]="0";
       if ($valjour["18 h"] =="") $valjour["18 h"]="0";
       if ($valjour["19 h"] =="") $valjour["19 h"]="0";
       if ($valjour["20 h"] =="") $valjour["20 h"]="0";
       if ($valjour["21 h"] =="") $valjour["21 h"]="0";
       if ($valjour["22 h"] =="") $valjour["22 h"]="0";
       if ($valjour["23 h"] =="") $valjour["23 h"]="0";
$sval = $valjour["0 h"].";".$valjour["1 h"].";".$valjour["2 h"].";".$valjour["3 h"].";".$valjour["4 h"].";".$valjour["5 h"].";".$valjour["6 h"].";".$valjour["7 h"].";".$valjour["8 h"].";".$valjour["9 h"].";".$valjour["10 h"].";".$valjour["11 h"].";".$valjour["12 h"].";".$valjour["13 h"].";".$valjour["14 h"].";".$valjour["15 h"].";".$valjour["16 h"].";".$valjour["17 h"].";".$valjour["18 h"].";".$valjour["19 h"].";".$valjour["20 h"].";".$valjour["21 h"].";".$valjour["22 h"].";".$valjour["23 h"];
$aaa=getcwd();
$aaa=1;
#print_r($aaa);
#$render->assign('img2url','../include/Plugins/vstat/src');
$render->assign('title',$title);
$render->assign('sval',$sval);
                                                  }

if ($period != '')  /* Show Visited links */
{
$xval  = $this->getValx("request",$reqdate,$period,$sites);
$vip   = $this->ProcessBarGraph('Visited pages',$xval,$period,$table,$reqdate);
$render->assign('vip',$vip);
}

if ($period != '')  /* Show Referers */
{
$xval  = $this->getValx("referer",$reqdate,$period,$sites);
$ref   = $this->ProcessBarGraph('Referers',$xval,$period,$table,$reqdate);
$render->assign('ref',$ref);
}

if ($period != '')  /* Show daily statistics only when month/sort */
{
$xval  = $this->getValx("provider",$reqdate,$period,$sites);
$prov  = $this->ProcessBarGraph('Providers',$xval,$period,$table,$reqdate);
$render->assign('prov',$prov);
}

                    /* /BODY II*/
return "index2.tpl.php";
                                                }    
/////////////////////////////////////////////////////////////////////////
//////////////////////////////////REQ FOR MAIN///////////////////////////
/////////////////////////////////////////////////////////////////////////

function getValx($arg0,$reqdate,$period,$sites) {
    $core = &getCoreInstance();
//    $db = $core->getProperty("db");

    $host = $_SESSION['nhost'];
    $usr = $_SESSION['nusr'];
    $passw = $_SESSION['npassw'];
    $db = $_SESSION['ndb'];

    
    $table_log = 'ez_zstat';
    $field = $arg0;

    $c = @mysql_connect($host,$usr,$passw) or die($msgSqlConnectImpossible);
    $ddb = @mysql_select_db($db) or die($msgBaseConnectImpossible);

    Switch($period) {
    case 'jour':
    $sql = "SELECT $field FROM $table_log WHERE DAYOFYEAR(date)=DAYOFYEAR(FROM_UNIXTIME('$reqdate')) order by $field ASC"; 
//    $result = $db->Exec($sql);
    $result = @mysql_query ($sql);
    break;
    case 'semaine':
    $sql = "SELECT $field FROM $table_log WHERE WEEK(date)=WEEK(FROM_UNIXTIME('$reqdate')) order by $field ASC"; 
//    $result = $db->Exec($sql);
    $result = @mysql_query ($sql);
    break;
    case 'mois':
    $sql = "SELECT $field FROM $table_log WHERE MONTH(date)=MONTH(FROM_UNIXTIME('$reqdate')) order by $field ASC"; 
//    $result = $db->Exec($sql);
    $result = @mysql_query ($sql);
    break;
            }
    $val_array = array("Total"=>0);
    $lastval = 'xxx';
    $i = 0;
    $nb_lastval = 1;

if ($field !="referer") {
        while ($row = @mysql_fetch_array ($result)) {
           if ($lastval == $row[$field]) {
             $nb_lastval += 1;
           } else {
                if ($i<>0) {
                      $val_array = $val_array + array("$lastval"=>$nb_lastval);
                      $nb_lastval=1;
                }
             }
           $lastval = $row[$field];
           $i += 1;
        }
  $val_array = $val_array + array("$lastval"=>$nb_lastval);
  $val_array["Total"] = $i;
 }  else {
        while ($row = @mysql_fetch_array ($result)) {
          if (  $row[0]!='' and !@eregi($sites[$table_log],$row[0])) {
             if ($lastval == $row[$field]) {
               $nb_lastval += 1;
             } else {
                  if ($i<>0) {
                        $val_array = $val_array + array("$lastval"=>$nb_lastval);
                        $nb_lastval=1;
                  }
               }
             $lastval = $row[$field];
             $i += 1;
          }
        }

  if (!@eregi($sites[$table_log],$lastval) and $lastval!="" ) {
     $val_array = $val_array + array("$lastval"=>$nb_lastval);
     $val_array["Total"] = $i;
    
  }
 
}


 arsort($val_array);
 @mysql_free_result ($result);
 @mysql_close ($c);
return $val_array;
                                            }



function ProcessEmptyEntry($table_log) {

    // Read the os_list and assign 2 arrays (label and id)

    $core = &getCoreInstance();
    $conf_table = $_SESSION['conf_table'];
    $db = $core->getProperty("db");
    $config = $db->Getall("Select * from $conf_table");

    foreach ($config as $k => $v) {
    if ($v['variable'] == 'os_list'){
    $config['os_list'] = $v['value'];}
                                    }
    $buffer = split ("\n",$config['os_list']);
   
    $i=0;
    foreach($buffer as $buffer1) {
       list ($os_id[$i], $os_label[$i]) = split ('[|]', $buffer1);
       $i+=1;
    }

    // Read the browser_list and assign 2 arrays (label and id)

    foreach ($config as $k => $v) {
    if ($v['variable'] == 'browser_list'){
    $config['browser_list'] = $v['value'];}
                                    }

    $buffer = split ("\n",$config['browser_list']);

    $i=0;
    foreach($buffer as $buffer1) {
        
       list ($browser_id[$i], $browser_label[$i]) = split ('[|]', $buffer1);
       $i+=1;
    }

    $host = $_SESSION['nhost'];
    $usr = $_SESSION['nusr'];
    $passw = $_SESSION['npassw'];
    
    $db = $core->config["DB"]["database"]; //$_SESSION['ndb'];
                    
    $cc = mysql_connect($host,$usr,$passw) or die($msgSqlConnectImpossible);
    $dddb = mysql_select_db($db,$cc) or die($msgBaseConnectImpossible." x ".mysql_error());

 # Fill country column
 $result = @mysql_query ("SELECT * from $table_log WHERE country='' ");
 
 while ($row = @mysql_fetch_array ($result)) {
    $newval=$this->ExtractCountry($row[host]);
       
    $req = @mysql_query("UPDATE $table_log SET country='$newval' where id='$row[id]' ");
 }

 # Fill provider column
 $result = @mysql_query ("SELECT * from $table_log WHERE provider='' ");
 while ($row = @mysql_fetch_array ($result)) {
    $newval=$this->ExtractProvider($row[host],$row[address]);
    $req = @mysql_query("UPDATE $table_log SET provider='$newval' where id='$row[id]' ");
 }
 # Fill os column
 $result = @mysql_query ("SELECT * from $table_log WHERE os='' ");
 while ($row = @mysql_fetch_array ($result)) {
    list($wb,$newval)=split(";",$this->ExtractAgent($row[agent],$browser_id,$browser_label,$os_id,$os_label));
    $req = @mysql_query("UPDATE $table_log SET os='$newval' where id='$row[id]' ");
 }

 # Fill wb column
 $result = @mysql_query ("SELECT * from $table_log WHERE wb='' ");
 while ($row = @mysql_fetch_array ($result)) {
    list($newval,$os)=split(";",$this->ExtractAgent($row[agent],$browser_id,$browser_label,$os_id,$os_label));
    $req = @mysql_query("UPDATE $table_log SET wb='$newval' where id='$row[id]' ");
 }

 @mysql_free_result ($result);
 # @mysql_free_result ($req);
 @mysql_close ($c);

 return True;
} # end of function ProcessEmptyEntry


##################################################################################
# Use this function to extract domain name from a Host name
#  $hst should be equal to @getHostByAddr($REMOTE_ADDR)
#  
# 
##################################################################################
function ExtractProvider($hst, $addressip) {
// global $msgOther;
 $msgOther = 'Unknown';

 $hst_array = split("[.]",$hst);
 $prov = $hst_array[sizeof($hst_array)-2].'.'.$hst_array[sizeof($hst_array)-1];
 if ($hst != $addressip) {
   if ($prov == "co.jp" or $prov == "co.uk" ) return $hst_array[sizeof($hst_array)-3].".".$prov;
     else return $prov ;
 } else return $msgOther;
}  #end of ExtractProvider

##################################################################################
# Use this function to extract country name from a Host name
#  $hst should be equal to @getHostByAddr($REMOTE_ADDR)
#  
##################################################################################
function ExtractCountry($hst) {
 // Global variables for SQL connection

 $msgSqlConnectImpossible = 'msgSqlConnectImpossible';
 $msgBaseConnectImpossible = 'msgBaseConnectImpossible';
 $msgSqlQuerryError = 'msgSqlQuerryError';
 $msgUnknown = 'unknown';

 $host = $_SESSION['nhost'];
 $usr = $_SESSION['nusr'];
 $passw = $_SESSION['npassw'];
 $db = $_SESSION['ndb'];

 $c2 = @mysql_connect($host,$usr,$passw) or die($msgSqlConnectImpossible);
 $db2 = @mysql_select_db($db) or die($msgBaseConnectImpossible);


 $hst_array = split("[.]",$hst);
 $lastval = $hst_array[sizeof($hst_array)-1];  # last value in host name
 $table_dom = "liste_domaines";
/*
 $c2 = @mysql_connect("$server","$user","$password") or die($msgSqlConnectImpossible);
 $db2 = @mysql_select_db("$base") or die($msgBaseConnectImpossible);
*/
 $req2 = @mysql_query("select description from $table_dom where domaine='$lastval' ") or die ($msgSqlQuerryError);

 # Check that extension exist and return country name
 # Otherwise return Unknown
 if (@mysql_numrows($req2) > 0)
   return @mysql_result($req2,0);
   else return $msgUnknown;
 @mysql_close ($c2);
}  # end of  ExtractCountry



##################################################################################
### Fonction de correction2 du nom de l'agent (navigateur et OS)
### Output syntax is a string like WebBrowser;OS
### You can extract OS and WebBrowser using:
### list($wb,$os)=split(";",ExtractAgent($HTTP_USER_AGENT));
### echo $wb."<br>";
### echo $os."<br>";
##################################################################################
function ExtractAgent($agt,$browser_id,$browser_label,$os_id,$os_label) {

  // Init default values
//  $new_agt_browser="???";   // Do not change these ??? . It is used in other scripts
  $new_agt_os="???";        // Do not change these ??? . It is used in other scripts
  $new_agt_browser="???";   // Do not change these ??? . It is used in other scripts
  $new_agt_os="???";        // Do not change these ??? . It is used in other scripts

  // Check for browser
  for ($cpt = 0; $cpt < count($browser_id) ; $cpt++) {
     if (@ereg($browser_id[$cpt],$agt)) $new_agt_browser=$browser_label[$cpt];
  }
  // Check for OS
  for ($cpt = 0; $cpt < count($os_id) ; $cpt++) {
     if (@ereg($os_id[$cpt],$agt)) $new_agt_os=$os_label[$cpt];
  }


  return($new_agt_browser.";".$new_agt_os);   # Systax is=  WebBrowser;OS
}   # End of function ExtraireAgent
##################################################################################


##################################################################################
# This function now count hits in history table and in current table
function MonthSort($table_log, $reqdate) {
 // Global variables for SQL connection

 $host = $_SESSION['nhost'];
 $usr = $_SESSION['nusr'];
 $passw = $_SESSION['npassw'];
 $db = $_SESSION['ndb'];

 $c = @mysql_connect($host,$usr,$passw) or die($msgSqlConnectImpossible);
 $ddb = @mysql_select_db($db) or die($msgBaseConnectImpossible);


 $msgSqlConnectImpossible = 'msgSqlConnectImpossible';
 $msgBaseConnectImpossible = 'msgBaseConnectImpossible';
 $msgMonthsArray = array("january","february","march","april","may","june","july","august","september","october","november","december");

 $today_array = getdate($reqdate);
 $req_month = $today_array["mon"];

 // Query in history table
 $table_log_h = $table_log."_h";
 $val_array = array("Total"=>0);
 $result = @mysql_query ("SELECT UNIX_TIMESTAMP(date),hits FROM $table_log_h order by date ASC");
// if ($result !="") $row = @mysql_fetch_array ($result);

 if ($result!= NULL) {
    while ($row = @mysql_fetch_array ($result)) {
       $date_array = getdate($row[0]);
       $val_array = $val_array + array($msgMonthsArray[$date_array["mon"]-1]." ".$date_array["year"]=>$row[hits]);
       $val_array["Total"] = $val_array["Total"] + $row[hits];
    } # end while
 }

  $last_month_h = $date_array["mon"];
  $last_year_h = $date_array["year"];

  // echo "Newest in history table=".$last_month_h." ".$last_year_h."<br>";
  // echo "Server Date=".date(m)." ".date(Y)."<br>";

  if ($last_month_h=='') {  //historay table is empty
    $result = @mysql_query ("select UNIX_TIMESTAMP(min(date)) from $table_log");
    if ($result !="") $row = @mysql_fetch_array ($result);
    $date_array = getdate($row[0]);
    $last_month_h = $date_array["mon"];
    $last_year_h = $date_array["year"];
    $last_month_h = $last_month_h - 1;
       if ($last_month_h==0) {
           $last_year_h = $last_year_h -1;
           $last_month_h=12;
       }

  }



  do {
       $last_month_h = $last_month_h + 1;
       if ($last_month_h==13) {
           $last_year_h = $last_year_h +1;
           $last_month_h=1;
       }
       $result = @mysql_query ("select count(*) from $table_log where month(date)=$last_month_h and year(date)=$last_year_h order by date asc");
       $row = @mysql_fetch_array ($result);
       $val_array = $val_array + array($msgMonthsArray[$last_month_h-1]." ".$last_year_h=>$row[0]);
       $val_array["Total"] = $val_array["Total"] + $row[0];
   }  while ( !($last_month_h==date(n) and $last_year_h==date(Y)));


 @mysql_free_result ($result);
 @mysql_close ($c);
 return $val_array;
}

##################################################################################
function DaySort($table_log, $reqdate, $period) {
 // Global variables for SQL connection

 $host = $_SESSION['nhost'];
 $usr = $_SESSION['nusr'];
 $passw = $_SESSION['npassw'];
 $db = $_SESSION['ndb'];

 $c = @mysql_connect($host,$usr,$passw) or die($msgSqlConnectImpossible);
 $ddb = @mysql_select_db($db) or die($msgBaseConnectImpossible);


 # select what to search for depending on selected period
 switch ($period) {
    case "semaine":
        $q_string = "SELECT UNIX_TIMESTAMP(date) FROM $table_log WHERE WEEK(date)=WEEK(FROM_UNIXTIME('$reqdate')) order by date ASC";
        $result = @mysql_query ($q_string);
        break;
    case "mois":
        $q_string = "SELECT UNIX_TIMESTAMP(date) FROM $table_log WHERE MONTH(date)=MONTH(FROM_UNIXTIME('$reqdate')) order by date ASC";
        $result = @mysql_query ($q_string);
       break;
 }
 $val_array = array("Total"=>0);
 $last_date_array = array(0,0,0,0,0,0,0,0,0,0);
 $nb_lastval = 1;
 $today_array = getdate($reqdate);
 $i = 0;
 while ($row = @mysql_fetch_array ($result)) {
    $date_array = getdate($row[0]);
    if ($date_array["year"] == $today_array["year"]) {
       if ($date_array["mon"] == $today_array["mon"]) {
              if (  ($last_date_array["mday"] == $date_array["mday"])  ) {
                 $nb_lastval += 1;
              } else {
                         if ($i<>0) {
                           $val_array = $val_array + array($last_date_array["mday"]."/".$last_date_array["mon"]."/".$last_date_array["year"]=>$nb_lastval);
                           $nb_lastval=1;
                         }
                     }
              $last_date_array = $date_array;
              $i += 1;
       }  # end if mon
    }  # end if year
 } # end while
 $val_array = $val_array + array($last_date_array["mday"]."/".$last_date_array["mon"]."/".$last_date_array["year"]=>$nb_lastval);
 $val_array["Total"] = $i;
 @mysql_free_result ($result);
 @mysql_close ($c);
 return $val_array;
}

##################################################################################

##################################################################################
function HourSort($table_log, $reqdate) {
 // Global variables for SQL connection

 $host = $_SESSION['nhost'];
 $usr = $_SESSION['nusr'];
 $passw = $_SESSION['npassw'];
 $db = $_SESSION['ndb'];

 $c = @mysql_connect($host,$usr,$passw) or die($msgSqlConnectImpossible);
 $ddb = @mysql_select_db($db) or die($msgBaseConnectImpossible);
 $result = @mysql_query ("SELECT UNIX_TIMESTAMP(date) FROM $table_log WHERE DAYOFYEAR(date)=DAYOFYEAR(FROM_UNIXTIME($reqdate)) order by date ASC");

 $val_array = array("Total"=>0);
 $last_date_array = array(0,0,0,0,0,0,0,0,0,0);
 $nb_lastval = 1;
 $today_array = getdate($reqdate);

 $i = 0;
 while ($row = @mysql_fetch_array ($result)) {
    $date_array = getdate($row[0]);
    if ($date_array["year"] == $today_array["year"]) {
       if ($date_array["mon"] == $today_array["mon"]) {
          if ($date_array["mday"] == $today_array["mday"]) {
              if (  ($last_date_array["hours"] == $date_array["hours"])  ) {
                 $nb_lastval += 1;
              } else {
                         if ($i<>0) {
                           $val_array = $val_array + array($last_date_array["hours"]." h"=>$nb_lastval);
                           $nb_lastval=1;
                         }
                     }
              $last_date_array = $date_array;
              $i += 1;
          }  # end if mday
       }  # end if mon
    }  # end if year
 } # end while

 $val_array = $val_array + array($last_date_array["hours"]." h"=>$nb_lastval);
 $val_array["Total"] = $i;
 @mysql_free_result ($result);
 @mysql_close ($c);
 return $val_array;
}

##################################################################################

};                 

?>